%This file generates a case of a 20x20 Cov-matrix with up to 10 sub blocks.
%10 sampled sequences of same length are generated for use in the
%worst-case objective function.
%The performance is measured for different number of blocks and different
%sample lengths.

clear, close all
NumOfStocks = 20;
randn('state',0);


%[CovBlocks, Combinations, SampleSizes, Sigma, StockReturns]=GetCovBlocks(0);
figure(1)
load data_10_blocks.mat

%Create 10 Sampled sequence of numbers. Maximum sample number = 10000.
Samples=randn(NumOfStocks,10000,10);

for iterBlocks=1:5
NumOfBlocks=2*iterBlocks;
error=[];

%Define the covariance blocks for this iteration instance
CovBlocksIter=CovBlocks(1:NumOfBlocks);
CombinationsIter=Combinations(1:NumOfBlocks);


%Run the iterations for different sample lengths
for iterSamples=1:5
%Define number of samples per block
NumOfSamples=iterSamples*1000*ones(1,NumOfBlocks);

%Define weights according to sample length, make them sum 1.
w=zeros(1,NumOfBlocks);
for i=1:NumOfBlocks
    w(1,i)=NumOfSamples(1,i)/sum(NumOfSamples);
end


for set=1:10
CovBlocksSampled{set} = addNoiseSamples(Samples, NumOfSamples, CovBlocksIter, CombinationsIter);
end

    cvx_begin
        cvx_quiet(true); 
        variable Sigma_hat(NumOfStocks, NumOfStocks) symmetric;
    
        %Define objective function
        f = 0;
        
        for q=1:NumOfBlocks
            temp=[];
            for a=1:10
                temp = [temp, w(1,q)*norm(Sigma_hat(CombinationsIter{q}, CombinationsIter{q})-CovBlocksSampled{a}{q},'fro')];           
            end
            f = f + max(temp);
        end
        minimize (f)
    
        subject to
        
        Sigma_hat == semidefinite(NumOfStocks)
     cvx_end
    
%Now test the result using frobenius norm

error(iterSamples)=norm(Sigma-Sigma_hat,'fro');
iterSamples
end

subplot(2,3,iterBlocks)
plot(1000*[1:iterSamples],error)
title(['Error in estimation using Frobenius norm with ',num2str(NumOfBlocks), ' sub blocks'])
xlabel('Number of samples for submatrices')
ylabel('Error in frobenius norm')

end
